package com.example.cmpe277stockdata.RSSFeeds;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.example.cmpe277stockdata.beans.NewsBean;
import com.example.cmpe277stockdata.constants.DataConstants;

public class NewsReader 
{
	public ArrayList<NewsBean> getNewsFields(String companySymbol)
	{
		String URLString = DataConstants.NEWS_RSS_FEED + companySymbol;
		ArrayList<NewsBean> newsBean = null;
		try {
			
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			URL u;
		
			u = new URL(URLString);
		
			Document doc = builder.parse(u.openStream());
			NodeList nodes = doc.getElementsByTagName("item");
			System.out.println(nodes.getLength());
			newsBean = new ArrayList<NewsBean>();
			for(int i=0;i<nodes.getLength();i++) 
			{
				NewsBean data = new NewsBean();
				Element element = (Element)nodes.item(i);	
				data.setNewsTitle(getElementValue(element,DataConstants.NEWS_TITLE));
				data.setNewsLink(getElementValue(element,DataConstants.NEWS_LINK));
				data.setPubDate(getElementValue(element,DataConstants.NEWS_PUB_DATE));
				data.setNewsDescription(getElementValue(element,DataConstants.NEWS_DESCRIPTION));
				newsBean.add(data);
			}
			return newsBean;
		} 
		catch (MalformedURLException e) 
		{
			System.err.println(e.getMessage());
		} 
		catch (SAXException e) 
		{
			System.err.println(e.getMessage());
		}
		catch (IOException e) 
		{
			System.err.println(e.getMessage());
		} 
		catch (ParserConfigurationException e)
		{
			System.err.println(e.getMessage());
		}
		return newsBean;
	}

	protected static String getElementValue(Element parent, String label)
	{
		return getCharacterDataFromElement((Element) parent
				.getElementsByTagName(label).item(0));
	}

	private static String getCharacterDataFromElement(Element e) 
	{
		try 
		{
			Node child = e.getFirstChild();
			if (child instanceof CharacterData) {
				CharacterData cd = (CharacterData) child;
				return cd.getData();
			}
		} 
		catch (Exception ex) {
			System.err.println(ex.getMessage());
		}
		return "";
	}
}
